﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;


namespace OpenAuth.App
{
    public class DefectInventoryApp : BaseApp<DefectInventory>
    {
        private RevelanceManagerApp _revelanceApp;
        private IAuth _auth;

        /// <summary>
        /// 加载列表
        /// </summary>
        public TableData Load(QueryDefectInventoryListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }

            var properties = loginContext.GetProperties("DefectInventory");

            if (properties == null || properties.Count == 0)
            {
                throw new Exception("当前登录用户没有访问该模块字段的权限，请联系管理员配置");
            }

            List<string> orgIdList = new List<string>(); ;
            if (!string.IsNullOrEmpty(request.OrgId))
            {
                var org = loginContext.Orgs.SingleOrDefault(u => u.Id == request.OrgId);
                foreach (Org item in loginContext.Orgs)
                {
                    if (item.CascadeId.Contains(org.CascadeId))
                    {
                        orgIdList.Add(item.Id);
                    }
                }
            }
            else
            {
                orgIdList = loginContext.Orgs.Select(u => u.Id).ToList();
            }


            var result = new TableData();
            IQueryable<DefectInventory> objs = UnitWork.Find<DefectInventory>(u => orgIdList.Contains(u.OrgId))
                .Include(u => u.Org)
                .Include(u => u.EquipmentInventory)
                .Include(u => u.User);
            if (!string.IsNullOrEmpty(request.key))
            {
                objs = objs.Where(u => u.Code.Contains(request.key));
            }
            var propertyStr = string.Join(',', properties.Select(u => u.Key));
            result.columnHeaders = properties;
            result.data = objs.OrderByDescending(u => u.CreateTime)
                .Skip((request.page - 1) * request.limit)
                .Take(request.limit).Select($"new ({propertyStr})");
            result.count = objs.Count();
            return result;
        }

        public List<EquipmentInventory> GetEquipList(string orgId)
        {
            return UnitWork.Find<EquipmentInventory>(u => u.OrgId == orgId).ToList();
        }

        public List<Category> GetDefectCategoryList()
        {
            return UnitWork.Find<Category>(u => u.TypeId == "DefectCategory" && u.Disabled == false).ToList();
        }

        public void Add(DefectInventory obj)
        {
            string code = DateTime.Now.ToString("yyyyMMdd");
            var defects = UnitWork.Find<DefectInventory>(u => u.Code.Contains(code)).OrderByDescending(u => u.CreateTime).ToList();
            int index = 0;
            if (defects.Count == 0)
            {
                index = 1;
            }
            else
            {
                string maxCode = defects.First().Code.Substring(8);
                index = Convert.ToInt32(maxCode) + 1;
            }

            code = code + index.ToString("00");
            obj.Code = code;
            obj.CreateTime = DateTime.Now;
            obj.Status = 0;
            Repository.Add(obj);
        }

        public void Update(DefectInventory obj)
        {
            UnitWork.Update<DefectInventory>(u => u.Id == obj.Id, u => new DefectInventory
            {
                OrgId = obj.OrgId,
                EquipmentInventoryId = obj.EquipmentInventoryId,
                CategoryId = obj.CategoryId,
                FindTime = obj.FindTime,
                RectifyTime = obj.RectifyTime,
                Describe = obj.Describe,
                Position = obj.Position
            });

        }

        public DefectInventoryView GetDetail(string id)
        {
            var defect = UnitWork.Find<DefectInventory>(u => u.Id == id)
                .Include(u => u.Org)
                .Include(u => u.EquipmentInventory)
                .Include(u => u.User).FirstOrDefault();
            var files = UnitWork.Find<UploadFile>(u => u.FileGuid == defect.FileGuid);
            return new DefectInventoryView
            {
                DefectInventory = defect,
                UploadFiles = files.ToList()
            };
        }

        public List<UploadFile> GetUploadFiles(string guid)
        {
            return UnitWork.Find<UploadFile>(u => u.FileGuid == guid).ToList();
        }

        public DefectInventoryApp(IUnitWork unitWork, IRepository<DefectInventory> repository,
            RevelanceManagerApp app, IAuth auth) : base(unitWork, repository)
        {
            _revelanceApp = app;
            _auth = auth;
        }
    }
}